<template>
  <Page class="authorize-form">
    <div class="authorize-body">
      <van-form ref="zxForm" validate-trigger="onBlur">
        <!-- 区域1 -->
        <div class="title">
          <span>基本信息</span>
        </div>
        <div>
          <div @click="getEnterpriseList">
            <van-field
              v-model="form.corpName"
              required
              name="proName"
              label="企业名称"
              clearable
              placeholder="请输入企业名称"
              input-align="right"
              :rules="[{ required: true, message: '请输入企业名称' }]"
              right-icon="search"
              @input="changeValue"
              disabled
            />
          </div>

          <div class="search-body" v-show="showSearch">
            <div
              v-for="(item, index) in bossList"
              :key="index"
              class="search-item"
              v-html="item.qymc"
              @click="selectOne(item)"
            ></div>
          </div>
          <van-field
            label-width="140"
            v-model="form.corpCredit"
            required
            disabled
            name="corpCredit"
            label="企业统一信用代码"
            placeholder="自动反显无需手填"
            input-align="right"
          />
          <van-field
            label-width="140"
            readonly
            required
            name="bankName"
            v-model="form.bankName"
            label="企业基本户开户行"
            :rules="[{ required: true, message: '请选择企业基本户开户行' }]"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            @click="openBank1"
          />
          <van-field
            label-width="140"
            v-model="form.legalName"
            required
            disabled
            name="legalName"
            label="机构法人"
            placeholder="自动反显无需手填"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.lagelPersonId2"
            required
            name="lagelPersonId2"
            label="法人身份证号"
            placeholder="请输入法人身份证号"
            :rules="PersonIdRules"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.legalPersonPhone"
            required
            name="legalPersonPhone"
            label="法人手机号"
            placeholder="请输入法人手机号"
            :rules="legalPersonPhoneRules"
            input-align="right"
          />

          <van-field
            label-width="140"
            v-model="form.water"
            name="water"
            label="收费单位(水)"
            placeholder="请输入"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.electric"
            name="electric"
            label="收费单位(电)"
            placeholder="请输入"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.gas"
            name="gas"
            label="收费单位(气)"
            placeholder="请输入"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.waterAccount"
            name="waterAccount"
            label="户号(水)"
            placeholder="请输入"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.electricAccount"
            name="electricAccount"
            label="户号(电)"
            placeholder="请输入"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.gasAccount"
            name="gasAccount"
            label="户号(气)"
            placeholder="请输入"
            input-align="right"
          />
          <!-- 区域2 -->
          <div class="title">
            <span>授权信息</span>
          </div>
          <van-field
            label-width="140"
            readonly
            required
            name="authobject"
            v-model="form.authobject"
            label="授权对象"
            :rules="[{ required: true, message: '授权对象不能为空' }]"
            input-align="right"
            placeholder="请选择"
            @click="openBank2"
          />
          <!-- @click="openBank2" -->
          <van-field
            readonly
            clickable
            required
            name="authdate"
            :value="form.authdate"
            input-align="right"
            label="查询期限"
            :rules="[{ required: true, message: '请选择查询期限' }]"
            placeholder="请选择"
          >
            <template #input>
              <div class="authdate_flex" slot="right-icon">
                <div class="left">
                  <van-icon name="notes-o" />
                  {{ form.startauthdate }}
                </div>
                至
                <div class="right" @click="authdateshowPicker = true">
                  <van-icon name="notes-o" />
                  {{ form.authdate }}
                </div>
              </div>
            </template>
          </van-field>
        </div>
        <!-- 人脸认证按钮 -->
        <button
          class="theme-btn"
          style="margin: 22px auto"
          @click="goFace"
          v-if="showFaceBtn"
        >
          人脸认证
        </button>
        <div class="autobook_div">
          <van-checkbox
            v-model="isreadchecked"
            disabled
            icon-size="22px"
            name="isreadchecked"
            :label-disabled="true"
            :rules="[{ required: true, message: '请先阅读授权书!' }]"
            @click="lookviewBookClick('2')"
            >我已阅读并同意</van-checkbox
          ><span class="autobook_span" @click="lookviewBookClick('2')"
            >《企业征信信息采集和查询授权书》</span
          >
        </div>
    
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="selectOptions"
            @confirm="onConfirm($event)"
            value-key="label"
            @cancel="showPicker = false"
          />
        </van-popup>
        <!-- <button
					class="theme-btn"
					style="margin: 22px auto"
					@click="nextStep"
					v-if="isLeafNode"
				>
					下一步
				</button> -->
      </van-form>
    </div>
    <div class="tip-success" v-if="!showFaceBtn && !cydn_loading">
      <!-- 征信授权已提交，等待系统审核... -->
       认证成功
    </div>
    <div style="width: 100%;height: 80px;">
          <!-- 地处留白 -->
        </div>
    <!-- 企业基本户开户行 -->
    <transition name="bottomToTop05">
      <bankList
        ref="bankList"
        v-if="showBank1"
        @cancel="cancel1"
        :bankList="bankList1"
        @clickConfirm="clickConfirm1"
      ></bankList>
    </transition>
    <!-- 授权对象 -->
    <transition name="bottomToTop05">
      <bankList
        ref="bankList"
        v-if="showBank2"
        @cancel="cancel2"
        :bankList="bankList2"
        @clickConfirm="clickConfirm2"
      ></bankList>
    </transition>
    <!-- 日期选择 -->
    <van-popup v-model="authdateshowPicker" position="bottom">
      <van-datetime-picker
        type="date"
        title="选择年月日"
        @confirm="authdateConfirm"
        @cancel="authdateshowPicker = false"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
    <!-- pdf -->
    <transition name="bottomToTop05">
      <view-pdf
        :pdfUrl="pdfUrl"
        :viewType="viewType"
        v-if="pdfIsShow"
        :isView="isView"
        @agreePdf="agreePdf"
      ></view-pdf>
    </transition>
    <!-- <button class="theme-btn" :class="{ disabled: canSub }" @click="submitForm">人脸认证</button> -->
    <div class="zhe-face" v-if="canLookFace">
      <van-loading size="24px" text-color="#0094ff" color="#0094ff" vertical
        >正在认证中，请稍后...</van-loading
      >
    </div>
    <div class="zhe-face1" v-if="cydn_loading">
      <van-loading
        size="44px"
        text-color="#fff"
        color="#fff"
        vertical
      ></van-loading>
    </div>
  </Page>
</template>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
import bankList from "@/components/authorize/bankList";
import {
  getOrderedBanks,
  getCorpNames,
  faceRecognition,
  faceRecognition_face,
  insertMes,
  getByID,
  selectAuthDeptList,
  generateAuthorization_zx,
  allOpenBankList,
  allBankList,
  jbxxList,
  addOnlineAuth,
  companyInfoList,
  id_number,
} from "@/interfaces/authorize";

import { token_cydn } from "@/interfaces/cydnQt";
import viewPdf from "@/components/authorize/viewPdf.vue";
import { Dialog } from "vant";
export default {
  name: "authorize",
  components: {
    bankList,
    viewPdf,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      // 征信form表单
      form: {
        corpName: "", // 企业名称
        corpCredit: "", // 企业统一信用代码
        legalName: "", // 机构法人
        lagelPersonId2: "",
        lagelPersonId: "", // 法人身份证
        legalPersonPhone: "", // 法人手机号
        startauthdate: "", // 开始时间
        authdate: "", // 结束时间
        authobject: "", // 授权对象
        authobjectId: "", // 授权对象id
        bankName: "", // 企业基本户开户行
        bankId: "", // 企业基本户开户行id

        // 非必填字段
        water: "",
        electric: "",
        gas: "",
        waterAccount: "",
        electricAccount: "",
        gasAccount: "",
      },
      // 微风企科技form表单
      wfFormList: [], // 动态表单
      wfForm: {
        // taxpayerId: '', // 纳税人识别号
      },
      nextWfForm: [], // 下一步的动态表单用于拼接
      wfRules: {}, // 规则
      treeId: "", // 模板id
      selectOptions: [], // 下拉内容
      applyInstr: "",
      selectBanklist2: [],
      bankList1: [],
      bankList2: [],
      showBank1: false,
      showBank2: false,
      radio: "0",
      bossList: [],
      showSearch: false,
      countdown: 0,
      countdownInterval: null,
      authdateshowPicker: false,
      minDate: "",
      maxDate: "",
      pdfIsShow: false, // 查看pdf
      isccancelpdf: false, // 是否可以关闭pdf
      isreadchecked: false, // 是否阅读了
      isLeafNode: false, // 是否展示下一步
      showFace: false, // 是否展示人脸按钮
      pdfUrl: "",
      isView: "2", // 是否阅读了，1是已阅读
      showPicker: false, // 下拉框的选择
      viewType: "",
      sqInfo: "",
      // 校验身份证号
      PersonIdRules: [
        {
          required: true,
          message: "法人身份证号不能为空",
          trigger: "onBlur",
        },
      ],
      legalPersonPhoneRules: [
        {
          required: true,
          message: "法人手机号不能为空",
          trigger: "onBlur",
        },
        {
          // 自定义校验规则
          validator: (value) => {
            return /^1[3456789]\d{9}$/.test(value);
          },
          message: "请输入正确格式的手机号!",
          trigger: "onBlur",
        },
      ],
      times: "",
      canLookFace: false,
      isSuccess: "",
      showFaceBtn: false,
      cydn_loading: false,
      area: "",
      araeJC: "zj",
    };
  },
  computed: {
    canSub() {
      return Object.values(this.form).some((val) => !val);
    },
  },
  created() {
    const area = this.getUrlParam("area");
    const zxForm = JSON.parse(localStorage.getItem("pageInfo")) || "";
    this.area = area || zxForm.area;
    console.log(this.area, "area");
    switch (area) {
      case "镇江市":
        this.araeJC = "zj";
        break;
      case "连云港市":
        this.araeJC = "lyg";
        break;
      default:
        break;
    }
    // 产业大脑授权判断
    // const id = this.getUrlParam('id_cydn');
    // if (id) {
    // 	this.getByID();
    // }
    // 数据反显

    this.dealData();
    this.initPage();
  },
  watch: {
    // 'form.corpName' (newval, oldval) {
    // },
    // 'form.amount'(newval, oldval) {
    // 	const test = newval ? newval.toString().replace(/^[0]+/, '') : 0;
    // 	this.form.amount = test;
    // 	// console.log(test)
    // 	if (test > 100000) this.form.amount = 100000;
    // 	if (test < 0) this.form.amount = 0;
    // },
  },
  destroyed() {
    clearInterval(this.countdownInterval);
  },
  methods: {
    async getByID() {
      this.cydn_loading = true;
      let param_token = {
        username: this.getUrlParam("phone"),
        platform: "miniApp",
      };
      const res_token = await token_cydn(param_token);
      if (res_token.code == 200) {
        // 更新state中的token_cydn
        this.$store.commit("user/setState", {
          attr: "token_cydn",
          data: res_token.token,
        });
      } else {
        this.$toast("登陆失败");
        return;
      }
      const params = {
        id: this.getUrlParam("id_cydn"),
      };
      const res = await getByID(params);
      if (res.code == 200) {
        console.log(res, "产业大脑税票详情");
        res.data.topDeptName = "中国工商银行股份有限公司苏州分行";
        const allCheck = await Promise.all([
          getCorpNames({ corpName: res.data.corpName }),
          // selectAuthDeptList({ deptAccount: "" })
        ]);
        console.log(allCheck, "allCheck");
        if (allCheck[0].code == 200) {
          if (allCheck[0].data.length > 0) {
            this.cydn_loading = false;
            this.selectOne(allCheck[0].data[0]);
            // 反显授权对象
            // const sqList = allCheck[1].data;
            const sqList = [
              {
                id: 1,
                deptName: "工商银行苏州分行",
                checkName: "中国工商银行",
                createTime: null,
                isDelete: "0",
                deptAccount: "GSYH",
              },
              {
                id: 2,
                deptName: "农业银行苏州分行",
                checkName: "中国农业银行",
                createTime: null,
                isDelete: "0",
                deptAccount: "nyyh-sqlr",
              },
              {
                id: 18,
                deptName: "苏州银行",
                checkName: "苏州银行",
                createTime: null,
                isDelete: "0",
                deptAccount: "SZ-ZXD",
              },
              {
                id: 25,
                deptName: "邮储银行苏州分行",
                checkName: "中国邮政储蓄",
                createTime: null,
                isDelete: "0",
                deptAccount: "psbc-cxsq",
              },
              {
                id: 26,
                deptName: "苏州农村商业银行",
                checkName: "苏州农村商业银行",
                createTime: null,
                isDelete: "0",
                deptAccount: "sznsh-sqlr",
              },
              {
                id: 27,
                deptName: "昆山农村商业银行",
                checkName: "昆山农村商业银行",
                createTime: null,
                isDelete: "0",
                deptAccount: "ks-sqlr",
              },
            ];
            const findOne = sqList.find(
              (pre) => res.data.topDeptName.indexOf(pre.checkName) > -1
            );
            // console.log(findOne, '12121212');
            if (findOne) {
              this.cydn_loading = false;
              this.form.authobjectId = findOne.deptAccount;
              this.form.authobject = findOne.deptName;
            } else {
              this.cydn_loading = false;
              this.$toast("您当前所在的银行暂未授权，请联系管理员");
            }
            // console.log(JSON.stringify(sqList));
          } else {
            this.cydn_loading = false;
            this.$toast("暂未查询到该企业");
          }
        }
      }
    },
    async getEnterpriseList() {
      let userId = this.getUrlParam("userId");
      let params = {
        source: "镇江市",
        userId: userId,
      };
      const res = await companyInfoList(params);
      console.log(res, "调接口了");
      this.bossList = res.data;
      if (this.bossList.length > 0) {
        this.showSearch = true;
      } else {
        Dialog.confirm({
          title: "提示",
          message: "未查询到企业是否跳转至小程序",
        })
          .then(() => {
            wx.miniProgram.navigateBack({ delta: 1 });
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    dealData() {
      const code = this.getQueryStringhash("code") || "";
      const zxForm = JSON.parse(localStorage.getItem("pageInfo")) || "";
      if (code == "0" && zxForm) {
        this.showFaceBtn = false;
        // 数据反显
        this.isView = zxForm.isView;
        this.isreadchecked = this.isView == "2" ? false : true;
        delete zxForm.isView;
        this.form = { ...this.form, ...zxForm };
        // console.log(this.form, 'form');
        // 征信数据存储
        this.saveNeedForms(this.form);
        // 微风企数据初始化
        // this.initWf();
      } else {
        // this.$toast('人脸认证失败')
        this.showFaceBtn = true;
      }
    },
    // 保存数据
    async saveNeedForms(zxForm) {
      // const params = {
      // 	corpName: zxForm.corpName,
      // 	corpCredit: zxForm.corpCredit,
      // 	khh: zxForm.bankName,
      // 	operManName: zxForm.legalName,
      // 	cerno: zxForm.lagelPersonId,
      // 	phone: '',
      // 	granter: zxForm.authobject,
      // 	startDate: zxForm.startauthdate,
      // 	endDate: zxForm.authdate,
      // 	taxAccount: '',
      // 	taxPsw: '',
      // 	createTime: zxForm.startauthdate,
      // 	filePath: '',
      // };
      let signDateArr = zxForm.startauthdate.split("-");
      let asDateArr = zxForm.authdate.split("-");
      const params = {
        companyName: zxForm.corpName,
        enterpriseCreditCode: zxForm.corpCredit,
        // 基本开户行
        openBank: zxForm.bankName,
        // 法人
        legalPerson: zxForm.legalName,
        // 手机号码
        legalPersonPhone: zxForm.legalPersonPhone,
        // 身份证号
        legalPersonIdNumber: zxForm.lagelPersonId,
        water: zxForm.water, //
        electric: zxForm.electric, //收费单位(电)
        gas: zxForm.gas, //收费单位(气)
        waterAccount: zxForm.waterAccount, //户号(水)
        electricAccount: zxForm.electricAccount, //户号(电)
        gasAccount: zxForm.gasAccount, //户号(气)
        // 开始日期
        startYear: signDateArr[0].slice(-2),
        startMonth: signDateArr[1],
        startDay: signDateArr[2],
        // 结束日期
        endYear: asDateArr[0],
        endMonth: asDateArr[1],
        endDay: asDateArr[2],
        // 人脸订单号
        orderId: this.getQueryStringhash("orderNo"),
        dataSource: 2,
        area: zxForm.area || this.area,
        // area: "镇江市",
        // 授权对象的标识
        bankCode: zxForm.authobjectId,
        // 授权对象名称
        bankName: zxForm.authobject,
      };
      console.log(this.area, "this.area");
      console.log(params, "generateAuthorization_zx");
      const res = await addOnlineAuth(params);
      // updateRecordById({
      // 	id: this.getUrlParam('id_cydn'),
      // 	creditAuth: '1', // 人脸授权成功后传此参数
      // 	// invoiceAuth: '1', // 发票授权成功后传此参数
      // 	// phoneNum: '15888811111', // 手机
      // });
      console.log(res, "insertMes");
      if (res.code != 200) {
        this.$toast(res.msg);
      } else {
        window.localStorage.removeItem("pageInfo");
      }
    },
    // 有#的情况
    getQueryStringhash(key) {
      let after = window.location.search;
      if (after.indexOf("?") === -1) return null; //如果url中没有传参直接返回空
      //key存在先通过search取值如果取不到就通过hash来取
      after = after.substr(1) || window.location.hash.split("?")[1];
      if (after) {
        let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        let r = after.match(reg);
        if (r != null) {
          return decodeURIComponent(r[2]);
        } else {
          return null;
        }
      }
    },
    getUrlParam(name) {
      const queryStr = String(window.location).split("?")[1] || "";
      name = encodeURIComponent(name);
      let arr = new RegExp("(^|&)" + name + "=([^&]*)(&|$)").exec(queryStr);
      if (arr) {
        return decodeURIComponent(RegExp.$2);
      } else {
        return "";
      }
    },

    openPopu(item) {
      // console.log(item, 'item');
      this.selectOptions = item.selectOptions;
      this.popuId = item.id;
      this.showPicker = true;
    },
    handleBlur(item) {
      // console.log(this.wfForm[item]);
      this.$forceUpdate();
    },
    agreePdf() {
      this.isView = "1";
      this.pdfIsShow = false;
      this.isreadchecked = true;
    },
    initPage() {
      this.form.startauthdate = this.$dayjs(new Date()).format("YYYY-MM-DD");
      this.form.authdate = this.$dayjs(new Date())
        .add(1, "year")
        .format("YYYY-MM-DD");
      this.minDate = new Date(this.$dayjs(new Date()).format("YYYY/MM/DD"));
      this.maxDate = new Date(
        this.$dayjs(new Date()).add(30, "year").format("YYYY/MM/DD")
      );
      // 获取开户行
      this.getBankList();
      // 获取授权对象
      this.getSqObj();
    },
    wfCompany() {
      // this.getBasicInfo();
    },
    authdateConfirm(value) {
      this.form.authdate = this.$dayjs(value).format("YYYY-MM-DD");
      this.authdateshowPicker = false;
    },
    async getBossList(timer) {
      // console.log(timer, 'timer');
      // this.showSearch = true
      const params = {
        name: this.form.corpName,
        area: this.area,
      };
      console.log(params, "params");
      const res = await jbxxList(params);
      console.log(res, "搜索的企业列表");
      if (this.timer === timer) {
        if (res.data.length > 0) {
          // if (res.data.length === 1) {
          //   this.form.corpName = res.data[0].corpName
          //   this.form.corpCredit = res.data[0].corpCredit
          // } else {
          res.data.forEach((ped) => {
            ped.viewName = this.deal(ped.d2CorpName);
          });
          this.showSearch = true;
          this.bossList = res.data;
          // }
          // console.log(this.bossList, 'bossList')
        } else {
          this.showSearch = false;
        }
      }
    },
    onConfirm($event) {
      // console.log($event);
      const e = this.popuId;
      this.wfForm[e] = $event.value;
      this.showPicker = false;
    },
    async taxationCir() {
      if (!this.hasAllPropertiesWithValues(this.wfForm)) return;
      this.canLookFace = true;
      const params = {
        ...this.wfForm,
        treeId: this.treeId,
        cburl: "",
      };
      console.log(params, "params");
      // 发票授权
      const res = await this.authorizeLogin(params);
      console.log(res, "发票授权");
      if (res.code == "200") {
        // 查询授权结果
        this.pollApi();
      } else {
        this.$toast(res.message);
      }
    },
    hasAllPropertiesWithValues(obj) {
      return Object.keys(obj).findIndex((pre) => !obj[pre]) === -1
        ? true
        : false;
    },
    async getBankList(name = "") {
      const params = {
        area: this.area,
      };
      console.log(params, "params");
      const res = await allOpenBankList(params);
      this.bankList1 = JSON.parse(JSON.stringify(res.data)).map((pre) => {
        return {
          bankId: pre.code,
          bankName: pre.name,
        };
      });
    },
    async getSqObj(name = "") {
      const params = {
        area: this.area,
      };
      const res = await allBankList(params);
      this.bankList2 = JSON.parse(JSON.stringify(res.data)).map((pre) => {
        return {
          bankId: pre.code,
          bankName: pre.name,
        };
      });
    },
    async handleGetVerificationCode(item) {
      // 根据type调用不同的sdk方法
      const sendType = {
        1: "sendCaptcha",
        2: "sendAuthCaptchaCodeSm",
        3: "sendAuthCaptchaCodeFp",
        4: "sendAuthCaptchaCodeTpass",
      };
      const type = sendType[item.sendSms.type];
      console.log(item, "item");
      if (this.countdown > 0) {
        return; // 如果倒计时还在进行中，则不执行获取验证码逻辑
      }
      // 执行获取验证码逻辑，例如发送请求到后端获取验证码
      const params = {
        password: this.wfForm.password,
        username: this.wfForm.username, // 身份证号码
        messageCountDown: item.sendSms.messageCountDown,
        // employees: this.wfForm.employees,
        apiUrl: item.sendSms.apiUrl,
        buttonLabel: item.sendSms.buttonLabel,
        type: item.sendSms.type,
      };
      const res = await this.sendSms(params, type);
      console.log(res, "res");
      if (res.code == "200") {
        // 开始倒计时
        this.countdown = +item.sendSms.messageCountDown;
        const _this = this;
        this.countdownInterval = setInterval(() => {
          this.countdown--;
          if (this.countdown === 0) {
            clearInterval(_this.countdownInterval); // 倒计时结束时清除定时器
          }
        }, 1000);
      } else {
        this.$toast(res.message);
      }
    },
    // 发送短信验证
    sendSms(params, apiName) {
      console.log(params, "短信验证");
      return new Promise((resolve, reject) => {
        authSdk[apiName](params).then((res) => {
          resolve(res);
        });
      });
    },
    // 获取授权基本信息
    getBasicInfo() {
      const params = {
        taxpayerId: this.wfForm.taxpayerId,
        channelCode: "51e2s",
      };
      console.log(params, "获取授权基本信息");
      return new Promise((resolve, reject) => {
        authSdk.getBasicInfo(params).then((res) => {
          resolve(res);
        });
      });
    },
    // 省份授权模板获取
    getAuthTemplate() {
      const params = {};
      console.log(params, "省份授权模板获取");
      return new Promise((resolve, reject) => {
        authSdk.getAuthTemplate(params).then((res) => {
          resolve(res);
        });
      });
    },

    // 获取身份信息
    getAuthIdentityInfo(params) {
      console.log(params, "获取身份信息");
      params.treeId = this.treeId;
      return new Promise((resolve, reject) => {
        authSdk.getAuthIdentityInfo(params).then((res) => {
          resolve(res);
        });
      });
    },
    // 打开授权书
    lookviewBookClick(item) {
      // 如果为1代表是动态生成的授权页面
      // 如果不为1则是pdf展示
      if (item === "1") {
        this.viewType = item;
        this.pdfUrl = this.sqInfo;
        this.pdfIsShow = true;
      } else {
        this.viewType = item;
        // this.pdfUrl = "/viewpdf.pdf";
        this.pdfUrl = `https://zx-1311146360.cos.ap-shanghai.myqcloud.com/face/${this.araeJC}.pdf`;
        this.pdfIsShow = true;
      }
    },
    deal(val) {
      if (this.form.corpName) {
        return val.replace(
          this.form.corpName,
          "<font style='color:#fd485e;'>" + this.form.corpName + "</font>"
        );
      } else {
        return val;
      }
    },
    // 选择某个企业
    async selectOne(item) {
      this.form.corpName = item.qymc;
      this.form.corpCredit = item.tyshxydm;
      this.form.legalPersonPhone = item.phone;

      this.form.legalName = item.name;
      // ==============
      // 获取身份证号
      let params = {
        source: this.area,
        userId: item.userId,
      };
      console.log(params, "传了啥");
      const res = await id_number(params);
      console.log(res, "怎么个事");
      this.form.lagelPersonId = res.data.idCard;
      if (res.data.idCard && res.data.idCard.length === 18) {
        // 使用正则表达式替换中间的四位数字为星号
        this.form.lagelPersonId2 = res.data.idCard.replace(
          /^(.{6})(.*)(.{4})/,
          "$1****$3"
        );
      }
      // =============
      this.showSearch = false;
    },

    // 微风企
    async initWf() {
      // 获取微风企科技授权基本信息
      this.wfForm.taxpayerId = this.form.corpCredit;
      const res = await this.getBasicInfo();
      console.log(res, "res");
      if (res.code === "200") {
        // 获取授权书
        this.sqInfo = res.data.taxAuthAgreement;
        const resTemplate = await this.getAuthTemplate();
        console.log(resTemplate, "resTemplate");
        // 获取动态表单value
        resTemplate.data.treeNode[0].card.keyValues
          .map((val) => val.id)
          .forEach((pre) => (this.wfForm[pre] = ""));
        console.log(this.wfForm, "wfForm");
        this.wfForm.taxpayerId = this.form.corpCredit;
        this.wfForm.companyName = this.form.corpName;
        // 模拟数据
        // this.wfForm.companyName = '江苏某某某某某有限公司';
        // this.wfForm.password = '12345678';
        // this.wfForm.username = '321234567891011121';
        // 获取规则
        this.wfRules = resTemplate.data.treeNode[0].rules;
        const ruleList = Object.values(this.wfRules);
        ruleList.forEach((pre) => {
          pre.forEach((pio) => {
            pio.trigger =
              pio.trigger === "blur"
                ? "onBlur"
                : pio.trigger === "change"
                ? "onChange"
                : pio.trigger;
          });
        });
        console.log(this.wfRules, "wfRules");
        // 取出动态表单数组
        this.wfFormList = resTemplate.data.treeNode[0].card.keyValues;
        this.wfFormList.forEach((pl) => {
          pl.required = resTemplate.data.treeNode[0].rules[pl.id][0].required;
        });
        // 模板id
        this.treeId = resTemplate.data.treeNode[0].id;
        console.log(this.treeId, "treeId");
        // 是否展示下一步
        this.isLeafNode = !resTemplate.data.treeNode[0].isLeafNode;
        this.showFace = resTemplate.data.treeNode[0].isLeafNode;
        // 下一步表单
        this.nextWfForm = this.isLeafNode
          ? resTemplate.data.treeNode[0].card.subNodes.card.keyValues
          : [];
        console.log(this.wfFormList, "wfFormList");
        // 特殊处理->身份信息固定为法定代表人
        this.wfFormList.forEach((pre) => {
          if (pre.id === "loginType") {
            pre.type = "input";
            pre.disabled = true;
            this.wfForm.loginType = "法定代表人";
          }
        });
        this.nextWfForm.forEach((pre) => {
          if (pre.id === "employees") {
            pre.type = "input";
            pre.disabled = true;
          }
        });
        console.log(this.nextWfForm, "nextWfForm");
      } else {
        this.$toast(res.message);
      }
    },

    cancel1() {
      this.showBank1 = false;
    },
    cancel2() {
      this.showBank2 = false;
    },
    clickConfirm1(item) {
      this.showBank1 = false;
      this.form.bankName = item.bankName;
      this.form.bankId = item.bankId;
    },
    clickConfirm2(item) {
      this.showBank2 = false;
      this.form.authobject = item.bankName;
      this.form.authobjectId = item.bankId;
    },
    nextStep() {
      if (!this.isreadchecked) {
        this.$toast("请先阅读授权书");
        return;
      }
      this.$refs.zxForm
        .validate()
        .then((result) => {
          console.log(this.form, "form");
          console.log(this.wfForm, "wfForm");
          this.nextWfStep(this.wfForm);
        })
        .catch((error) => {
          console.log(error, "error");
        });
    },
    // 微风授权登录
    authorizeLogin(params) {
      return new Promise((resolve, reject) => {
        authSdk.authorizeLogin(params).then((res) => {
          resolve(res);
        });
      });
    },
    async goFace() {
      if (!this.form.corpName || !this.form.bankName || !this.form.authobject)
        return;
      // 首先判断是否阅读
      if (this.isView === "1") {
        this.cydnFace();
      } else {
        this.$toast("请先阅读授权书");
      }
    },
    async pollApi() {
      this.times++;
      // 3、轮询查询授权的结果
      const resultWf = await this.getAuthrizeResult();
      console.log(resultWf, "轮询查询授权的结果");
      if (resultWf.code == "200") {
        // 授权成功
        this.canLookFace = false;
        this.$toast("发票授权成功");
        window.localStorage.removeItem("pageInfo");
      } else {
        // 再次查询
        if (this.times > 120) {
          this.canLookFace = false;
          this.$toast("发票授权失败，请完善信息");
          window.localStorage.removeItem("pageInfo");
        } else {
          const _this = this;
          setTimeout(() => {
            _this.pollApi();
          }, 1000);
        }
      }
    },
    // 获取授权结果
    getAuthrizeResult(params = {}) {
      return new Promise((resolve, reject) => {
        authSdk.getAuthrizeResult(params).then((res) => {
          resolve(res);
        });
      });
    },
    async zxFace() {
      let area = this.area;
      const params = {
        name: this.form.legalName,
        idNo: this.form.lagelPersonId,
        callBackUrl: `https://fintech-zscqzy.szjrgzjg.com/#/faceSingle?code=&orderNo=&h5faceId=&newSign=&area=${area}`,
        // callBackUrl:
        // 	'http://192.168.1.100:8989/#/attestation?code=&orderNo=&h5faceId=&newSign=',
      };
      console.log(param, "callBackUrl");
      const res = await faceRecognition(params);
      // const res = {
      // 	faceUrl: 'https://www.baidu.com'
      // 	// faceUrl: 'http://192.168.1.100:8989/#/attestation?code=&orderNo=&h5faceId=&newSign='
      // }
      console.log(res, "faceUrl");

      if (res && res.faceUrl) {
        // 保存微风需要的授权参数
        // localStorage.setItem(
        // 	'wfForm',
        // 	JSON.stringify({
        // 		...this.wfForm,
        // 		treeId: this.treeId,
        // 		cburl: '',
        // 	})
        // );
        // 保存页面数据
        localStorage.setItem(
          "pageInfo",
          JSON.stringify({ ...this.form, isView: this.isView, area: area })
        );
        window.location.href = res.faceUrl;
      } else {
        this.$toast("姓名和身份证号不匹配");
      }
    },
    async cydnFace() {
      const params = {
        name: this.form.legalName,
        idNo: this.form.lagelPersonId,
        callBackUrl:
          // 'https://fintech-zscqzy.szjrgzjg.com/#/faceSingle?code=&orderNo=&h5faceId=&newSign=',
          // callBackUrl:
          `https://fintech-zscqzy.szjrgzjg.com/#/faceSingle?code=&orderNo=&h5faceId=&newSign=&area=${this.area}`,
      };
      console.log(params, "params");
      const res = await faceRecognition_face(params);
      // const res = {
      // 	faceUrl: 'https://www.baidu.com'
      // 	// faceUrl: 'http://192.168.1.100:8989/#/attestation?code=&orderNo=&h5faceId=&newSign='
      // }
      console.log(res, "新版人脸");
      if (res && res.faceUrl) {
        // 保存微风需要的授权参数
        // localStorage.setItem(
        // 	'wfForm',
        // 	JSON.stringify({
        // 		...this.wfForm,
        // 		treeId: this.treeId,
        // 		cburl: '',
        // 	})
        // );
        // 保存页面数据
        localStorage.setItem(
          "pageInfo",
          JSON.stringify({ ...this.form, isView: this.isView, area: this.area })
        );
        window.location.href = res.faceUrl;
      } else {
        this.$toast("姓名和身份证号不匹配");
      }
    },
    async nextWfStep(params) {
      // 获取身份信息
      const res = await this.getAuthIdentityInfo(params);
      if (res.code == "200") {
        console.log(res, "res获取身份信息");
        // 对employees下拉框进行赋值
        // const oneObj = this.nextWfForm.find((val) => val.id === 'employees');
        // oneObj.selectOptions = res.data.employees;
        // 找出法定代表人
        const oneObj = res.data.employees.find(
          (pre) => pre.value.indexOf("法定代表人") > -1
        );
        this.wfForm.employees = oneObj.value;
        this.wfFormList.push(...this.nextWfForm);
        this.isLeafNode = false;
        this.showFace = true;
        this.$forceUpdate();
      } else {
        this.$toast(res.message);
      }
    },
    // async submitForm() {
    // 	// 校验一些信息的填写格式是否真正确
    // 	// 校验手机号码
    // 	const identification = utils.regExp.get('identification');
    // 	if (!identification.test(this.form.lagelPersonId)) {
    // 		this.$toast('请先输入正确的身份证');
    // 		return;
    // 	}
    // 	if (!this.canSub) {
    // 		this.form.amount = this.form.amount + '';
    // 		const params = {
    // 			...this.form,
    // 			applyInstr: this.applyInstr,
    // 		};
    // 		console.log(params, '提交的内容');
    // 		const res = await insertFinance(params);
    // 		console.log(res, 'res');
    // 		if (res.code == 200) {
    // 			Dialog.alert({
    // 				title: '',
    // 				message: '您的需求已提交至意向银行，请继续完善问卷调查！',
    // 				theme: 'round-button',
    // 				confirmButtonColor: '#008ef0',
    // 			}).then(() => {
    // 				this.$router.push({
    // 					name: 'question',
    // 					query: {
    // 						id: res.data,
    // 					},
    // 				});
    // 			});
    // 		}
    // 	}
    // },
    openBank1() {
      this.showBank1 = true;
    },
    openBank2() {
      this.showBank2 = true;
    },
    changeSearch() {
      this.showSearch = true;
    },
    changeValue() {
      this.form.corpCredit = "";
      this.form.legalName = "";
      this.wfFormList = [];
      this.wfForm = {};
      // 代码实现
      if (this.form.corpName.length > 3) {
        this.timer = new Date().getTime();
        this.getBossList(this.timer);
      } else {
        this.showSearch = false;
      }
    },
    // 有#的情况
    getQueryStringhash(name) {
      const queryStr = String(window.location).split("?")[1] || "";
      name = encodeURIComponent(name);
      let arr = new RegExp("(^|&)" + name + "=([^&]*)(&|$)").exec(queryStr);
      if (arr) {
        return RegExp.$2;
      } else {
        return "";
      }
    },
  },
};
</script>
<style>
.van-field--error .van-field__control,
.van-field--error .van-field__control::placeholder {
  color: #c8c9cc;
}

.van-field__error-message {
  text-align: right;
}
</style>
<style lang="scss" scoped>
@import "@/assets/css/demo/index.scss";

.authorize-top {
  height: 139px;
  border: 0.5px solid transparent;
  background-image: url("https://zx-1311146360.cos.ap-shanghai.myqcloud.com/wx_h5/wx_h5_top.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;

  .authorize-top-title1 {
    margin: 40px 0 0 28px;
    font-size: 21px;
    font-family: Source Han Sans SC;
    font-weight: 500;
    color: #ffffff;
  }

  .authorize-top-title2 {
    margin: 6px 0 0 28px;
    font-size: 17px;
    font-family: Source Han Sans SC;
    font-weight: 500;
    color: #ffffff;
  }
}

.authorize-form {
  position: relative;
  padding-bottom: 20px;
  height: 100%;
  overflow-y: auto;

  // border: 1px solid red;
  .title {
    width: 100%;
    height: 30px;
    background-image: url("~img/authorize/titlebg.png");
    background-size: cover;
    padding-left: 38px;
    line-height: 30px;

    span {
      font-size: 14px;
      font-weight: 550;
      color: #5094eb;
    }
  }
}

input {
  background: none;
  outline: none;
  border: none;
  text-align: right;
}

input:focus {
  border: none;
}

.bank_input {
  width: 200px;
  // border: 1px solid #e0e1e5;
  // padding: 10px 10px;
  padding-right: 8px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  .right-img {
    width: 4px;
    height: 8px;
    // border: 1px solid red;
    // position: relative;
    // bottom: -5px;
  }

  .bank_tag {
    // margin-bottom: 7px;
    // margin-right: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #999999;
    // background: #f5f5f5;
    // height: 34px;
    padding: 0 5px;
    font-size: 14px;

    .bank-tag-icon {
      margin-left: 4px;
      font-size: 16px;
    }
  }
}

.selecttext {
  // width: 500rpx;
  height: 30px;
  line-height: 30px;
  text-align: right;
  color: #999999;
  font-size: 12px;
  font-family: Alibaba PuHuiTi;
  color: #999999;
}

.right-is {
  display: flex;
  justify-content: flex-end;
}

.search-body {
  position: absolute;
  top: 72px;
  right: 10px;
  width: 240px;
  max-height: 200px;
  // border: 1px solid red;
  background: #fff;
  z-index: 100;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  padding-bottom: 10px;

  .search-item {
    margin: 4px 0 0 8px;
    font-size: 12px;
    font-family: Alibaba PuHuiTi;
    color: #999999;
  }
}

.linkman_input {
  width: 140px;
}

.description {
  // width: 90%;
  text-align: center;

  textarea {
    width: 90%;
    padding: 4px;
    font-size: 14px;
  }
}

.authdate_flex {
  display: flex;
  font-size: 12px;

  .left {
    margin-right: 5px;
    // background-color: #f4f4f4;
    border-radius: 2px;
    padding: 0 5px;
    color: #999999;
  }

  .right {
    background-color: #f4f4f4;
    border-radius: 2px;
    padding: 0 10px;
    color: #999999;
    margin-left: 5px;
    font-size: 12px;
    box-sizing: border-box;
  }
}

.yzm-btn {
  width: 80px;
  height: 22px;
  background: #5094eb;
  border-radius: 5px;
  color: #fff;
  margin-left: 5px;
  font-size: 12px;
  // border: none;
}

// button ::after {
//   border: none;
// }
.autobook_div {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin: 0px 10px;
  font-size: 12px;

  // border: 1px solid red;
  .autobook_span {
    color: #5094eb;
    cursor: pointer;
    position: relative;
    line-height: 20px;
    // top: -2px;
  }

  /deep/.van-checkbox__label--disabled {
    color: #333;
  }

  /deep/.van-checkbox__icon--checked .van-icon {
    color: #fff;
    background-color: #1989fa;
    border-color: #1989fa;
  }
}

.zhe-face {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 999;
  background: rgba(82, 80, 80, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
}
.zhe-face1 {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 999;
  background: rgba(82, 80, 80, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}
.tip-success {
  margin: 50px auto;
  text-align: center;
  font-size: 20px;
  color: #1989fa;
}
</style>
